package hui.zhang.utils;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.springframework.data.domain.Page;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 让Action继承本类，实现模型驱动封装和分页的相关处理
 * @author hui.zhang
 * @date 2017年12月12日 下午9:05:32
 * @param <T>
 */
@SuppressWarnings("all")
public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T>{

	protected T model;
	public T getModel() {
		return model;
	}
	public BaseAction() {
		Type genericSuperclass = this.getClass().getGenericSuperclass();
		ParameterizedType parameterizedType = (ParameterizedType)genericSuperclass;
		Class<T> modelClass = (Class<T>)parameterizedType.getActualTypeArguments()[0];
		try {
			model = modelClass.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			throw new RuntimeException("模型构造失败！");
		}
	}
	
	//分页
	protected Integer page;
	protected Integer rows;
	public void setPage(Integer page) {
		this.page = page;
	}
	public void setRows(Integer rows) {
		this.rows = rows;
	}
	
	/**
	 * 把分页数据转成json并响应到页面
	 * @param pageData
	 */
	protected void toJsonAndResponse(Page<T> pageData) {
		try {
			// 修改全局的全局日期格式  
			JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("total", pageData.getTotalElements());
			map.put("rows", pageData.getContent());
			String jsonString = JSONObject.toJSONString(map, SerializerFeature.WriteDateUseDateFormat);
			ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 将数据转成json并响应到浏览器
	 * @param c
	 */
	protected void toJsonAndResponse(Object obj) {
		try {
			// 修改全局的全局日期格式  
			JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
			String jsonString = JSONObject.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
			ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (IOException e) {
			throw new RuntimeException("出现异常！",e);
		}
	}
	
	

}
